// Set config defaults when creating the instance
import axios from "axios";
import {showFailToast} from "vant";
import router from "../config/router";




const myAxios = axios.create({
    // @ts-ignore
    baseURL: process.env.NODE_ENV === "development" ? 'http://localhost:8080/api' : 'http://47.122.115.126:9999/api',
    // baseURL: 'http://localhost:8080/api/',
});

myAxios.defaults.withCredentials = true; // 允许携带 cookie
// 添加请求拦截器
myAxios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    // console.log("我要发送请求了,",config)
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
myAxios.interceptors.response.use(function (response) {
    const data = response.data;
    // 对响应数据做点什么
    // console.log("我收到你的响应了,",response?.data)
    if(response?.data?.code === 0){
        //console.log( process.env.NODE_ENV);
        return response?.data
    }
    //未登录则跳转到登录项
    else if(response?.data?.code === 40100){
        showFailToast("请先登录");
        // const redirectUrl = window.location.href;
        // window.location.href  = `/user/login?redirect=${redirectUrl}`;
        router.push("/user/login").catch(e => console.log(e))
    }else if(data.code === 40101){
        showFailToast(data.description);
        router.back();
    }else{
        showFailToast(data.description);
    }
}, function (error) {
    // 对响应错误做点什么
    showFailToast("服务器超时 请重试");
    //router.push("/user/login").catch(e => console.log(e))
    return Promise.reject(error);
});
export default myAxios;